package cn.com.taiji.pos.controller;

import cn.com.taiji.pos.entity.*;
import cn.com.taiji.pos.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/Food")
public class FoodController {

    @Value("${FOOD_CATEGORY_ID_CODE_xmb}")
    private String FOOD_CATEGORY_ID_CODE_xmb;
    @Autowired
    private IMenuFoodItemService menuFoodItemService;
    @Autowired
    private IMenuFoodCategoryService menuFoodCategoryService;
    @Autowired
    private IConfigMealTimeService configMealTimeService;
    @Autowired
    private ISystemFoodNotesService systemFoodNotesService;
    @Autowired
    private IConfigBusinessTypeService configBusinessTypeService;


    /**
     * 查询所有菜品
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "allFood", method = RequestMethod.POST)
    public String allFood(Model model, HttpServletRequest request, HttpServletResponse response) {
        //POS机包含业务类型id
        String physicalCode = request.getParameter("physicalCode");
        List<ConfigBusinessType> configBusinessTypeList = configBusinessTypeService.getListForType(physicalCode);
        List<String> idList = configBusinessTypeList.stream().map(ConfigBusinessType::getId).collect(Collectors.toList());
//        List<String> idList =(List<String>) WebUtils.getSessionAttribute(request, "configBusinessTypeList");
        String canci = request.getParameter("canci");
        List<MenuFoodItem> foodItemList1 = menuFoodItemService.listFood(FOOD_CATEGORY_ID_CODE_xmb, canci);
        List<MenuFoodCategory> categoryList = menuFoodCategoryService.query().ne("CODE", FOOD_CATEGORY_ID_CODE_xmb).orderByAsc("SORT_NO").list();
        List<MenuFoodItem> allFoodItemList = new ArrayList<>(foodItemList1);
        //菜品分类
        boolean flag = true;
        for (MenuFoodCategory category : categoryList) {
            List<MenuFoodItem> foodItemList = new ArrayList<>();
            for (MenuFoodItem item : foodItemList1) {
                if (idList.contains(item.getBusinessTypeId()) && item.getFoodCategoryId().equals(category.getId())) {
                    foodItemList.add(item);
                } else if (!idList.contains(item.getBusinessTypeId()) && flag) {
                    allFoodItemList.remove(item);
                }
            }
            category.setMenuFoodItemList(foodItemList);
            flag = false;
        }
        model.addAttribute("canci", canci);
        model.addAttribute("result", "success");
        model.addAttribute("categoryList", categoryList.stream().filter(i -> i.getMenuFoodItemList().size() > 0).collect(Collectors.toList()));
        model.addAttribute("allFoodItemList", allFoodItemList);
        return JSONObject.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 刷新菜品
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "RefreshAllFood", method = RequestMethod.POST)
    public String refreshAllFood(Model model, HttpServletRequest request, HttpServletResponse response) {
        String physicalCode = request.getParameter("physicalCode");
        List<ConfigBusinessType> configBusinessTypeList = configBusinessTypeService.getListForType(physicalCode);
        List<String> idList = configBusinessTypeList.stream().map(ConfigBusinessType::getId).collect(Collectors.toList());
//        List<String> idList =(List<String>) WebUtils.getSessionAttribute(request, "configBusinessTypeList");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss");
        QueryWrapper<ConfigMealTime> configMealTimeWrapper = new QueryWrapper<>();
        configMealTimeWrapper.le("START_TIME", df.format(LocalTime.now())).ge("END_TIME", df.format(LocalTime.now())).orderByAsc("SORT_NO");
        ConfigMealTime configMealTime = configMealTimeService.list(configMealTimeWrapper).get(0);
        List<MenuFoodItem> foodItemList1 = menuFoodItemService.listFood(FOOD_CATEGORY_ID_CODE_xmb, configMealTime.getName());
        List<MenuFoodCategory> categoryList = menuFoodCategoryService.query().ne("CODE", FOOD_CATEGORY_ID_CODE_xmb).orderByAsc("SORT_NO").list();
        List<MenuFoodItem> allFoodItemList = new ArrayList<>(foodItemList1);
        //菜品分类
        boolean flag = true;
        for (MenuFoodCategory category : categoryList) {
            List<MenuFoodItem> foodItemList = new ArrayList<>();
            for (MenuFoodItem item : foodItemList1) {
                if (idList.contains(item.getBusinessTypeId()) && item.getFoodCategoryId().equals(category.getId())) {
                    foodItemList.add(item);
                } else if (!idList.contains(item.getBusinessTypeId()) && flag) {
                    allFoodItemList.remove(item);
                }
            }
            category.setMenuFoodItemList(foodItemList);
            flag = false;
        }
        model.addAttribute("canci", configMealTime.getName());
        model.addAttribute("result", "success");
        model.addAttribute("categoryList", categoryList.stream().filter(i -> i.getMenuFoodItemList().size() > 0).collect(Collectors.toList()));
        model.addAttribute("allFoodItemList", allFoodItemList);
        return JSONObject.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 查询菜品备注
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "getFoodNotes", method = RequestMethod.POST)
    public String getFoodNotes(@RequestBody Map<String, String> paramMap, HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<SystemFoodNotes> systemFoodNotesList = systemFoodNotesService.query().eq("STATUS", 0).eq("CATEGORY_ID", paramMap.get("categoryId")).list();
        List<List<String>> danNotesList = new ArrayList<>();
        List<String> duoNotesList = new ArrayList<>();
        for (SystemFoodNotes systemFoodNotes : systemFoodNotesList) {
            if (systemFoodNotes.getName().contains("@")) {
                //单选标签组
                List<String> notes;
                notes = Arrays.asList(systemFoodNotes.getName().replaceAll("\\{", "").replaceAll("\\}", "").split("@"));
                danNotesList.add(notes);
            } else {
                //多选标签
                duoNotesList.add(systemFoodNotes.getName());
            }
        }
        resultMap.put("danNotesList", danNotesList);
        resultMap.put("duoNotesList", duoNotesList);
        return JSONObject.toJSONString(resultMap);

    }


}
